import './SignUpLoading.scss'

import { v4 } from 'uuid'
import { App } from 'antd'
import { useMount } from 'ahooks'
import { useRequest } from 'alova/client'
import { useEffect, useState, lazy, Suspense } from 'react'
import { useNavigate } from 'react-router-dom'

import { Http } from '../../Utils/Api'
import { getSignUpBack } from '../../Utils'
import { Decrypt, PutIndexedDB, GetIndexedDB } from '../../Utils/IndexedDB'
import { UserAvatar, UserBackboard } from '../../Config/theme'
import { modelStore, drawerStore, fromStore } from '../../Config/zustand'

const LoadSvg = lazy(() => import('../../Page/Loading/LoadSvg'))


const SignUpLoading = ({ data, Off }) => {

    const [QRUuid] = useState(v4())
    const Navigate = useNavigate()
    const { notification } = App.useApp()
    const { updateModel } = modelStore()
    const { updateDrawer } = drawerStore()
    const { updateFromData } = fromStore()
    const [Status, setStatus] = useState(false)
    const [UserInfo, setUserInfo] = useState({})
    const [UserAdd, setUserAdd] = useState({})

    const [ThirdParty, setThirdParty] = useState()

    const [LoadingTemp, setLoadingTemp] = useState()

    const { send } = useRequest(data => Http(data), { immediate: false })

    useMount(async () => {
        const { theme } = await Decrypt(localStorage.getItem('project'))
        const loading = lazy(() => import(`../../Page/Loading/${theme.loadPage}.jsx`))
        setLoadingTemp(loading)
        updateModel({})
        updateDrawer({})
        updateFromData({})
        signUp()
    })



    const tokenFunc = async (token) => {
        const params = await getSignUpBack(token)

        console.log(params)
        if (params) {
            const { user, userAdd, menu } = params
            if (user.isDefaultPassword) {
                updateModel({ type: 'CommonModel', title: '修改默认密码', width: 640, close: true, data: { user: { ...user, ...data }, type: 'ResetPassword' } })
                return false
            }
            const admin = menu.find(v => v.uuid === '10000000-0000-0000-0000-000000000000')
            const start = menu.find(v => v.uuid === '20000000-0000-0000-0000-000000000000')
            if (admin && start) {
                setUserAdd(userAdd)
                setUserInfo(user)
                setStatus(true)
            }
            else if (admin) onNavTo('Admin')
            else if (start) onNavTo('Start')
        } else {
            notification.error({ message: '登录失败!', description: '请确认帐号或密码!', key: 'start' })
            Off()
        }
    }

    const signUp = async (uuid) => {
        if (data?.username && data?.password) {
            try {
                const token = await send({ method: 'post', url: 'authLogin/Login', params: { ...data, organizationUuid: uuid } })
                tokenFunc(`${token.data.token_type} ${token.data.access_token}`)
            } catch (err) {
                Off()
            }
        } else if (data?.token) tokenFunc(token)
        else if (data?.ThirdParty) {
            setThirdParty(data.ThirdParty)
            if (data.ThirdParty === 'weChat') {
                const appid = 'wxa3d0c46c8bfcef89'
                const redirect_uri = 'https://common-redirect.ljkjkf.com'

                const { client_Id } = await Decrypt(localStorage.getItem('config'), true)
                const state = `${QRUuid}@${appid}@${client_Id}@true`
                const get = `${sessionStorage.getItem('API')}/users/GetOpenUnionidOrTokenSSE?QRUuid=${QRUuid}&Type=token`
                const codeData = {
                    self_redirect: true,
                    id: 'QRcode',
                    appid,
                    scope: 'snsapi_login',
                    response_type: 'code',
                    redirect_uri: window.encodeURI(redirect_uri),
                    state: state,
                    style: 'black',
                    href: 'https://image.ljkjkf.com/intellisiteSystem_TieKe/WebTemplate/code.css',
                }

                var eventSource = new EventSource(get)
                eventSource.onopen = () => new window.WxLogin(codeData)
                eventSource.onmessage = e => {
                    const { data } = e
                    if (data === 'dateOver') {
                        notification.error({ message: '登录失败!', description: '用户已过期请联系管理员!', key: 'start' })
                        eventSource.close()
                        Off()
                        return
                    }
                    if (data !== '0') {
                        tokenFunc(data)
                        eventSource.close()
                    }
                }
                eventSource.onerror = (err) => {
                    eventSource.close()
                    notification.error({ message: '登录失败!', description: '扫码登录失败!', key: 'start' })
                    Off()
                }
            }
        }
    }

    const onNavTo = (e) => Navigate(`/${e}`)

    return (
        <Suspense>
            <div className='SignUpLoading'>
                {Status ?
                    <div className='UserBox'>
                        <img src={UserBackboard[UserAdd.backImage]} alt="" />
                        <div>
                            <svg fill="none" viewBox="0 0 144 62" xmlns="http://www.w3.org/2000/svg">
                                <path fill="#dee2e5" d="m111.34 23.88c-10.62-10.46-18.5-23.88-38.74-23.88h-1.2c-20.24 0-28.12 13.42-38.74 23.88-7.72 9.64-19.44 11.74-32.66 12.12v26h144v-26c-13.22-.38-24.94-2.48-32.66-12.12z" fillRule="evenodd" />
                            </svg>
                            <img src={UserAvatar[UserAdd.avatar]} alt="" />
                            <div>
                                <div>{UserInfo?.roleName}</div>
                                <div>{UserInfo?.userName}</div>
                            </div>
                            <div>
                                <button className="btn" onClick={() => onNavTo('Admin')}>后台</button>
                                <button className="btn" onClick={() => onNavTo('Start')}>大屏</button>
                            </div>
                        </div>
                    </div> : ThirdParty ?
                        <div id="QRcode" /> :
                        LoadingTemp && <LoadingTemp style={{ '--background': 'transparent', '--stroke': '#212121', height: '100%' }} />

                }
            </div>
        </Suspense>
    );
};

export default SignUpLoading;